#!/bin/bash

source ./ek.env
home=$ALBERTMU_EK_WORKSPACE
[ -d $home ] && rm -rf $home
mkdir -p ${home}/logs ${home}/data ${home}/plugins && chmod 777 -R $home
docker run -d --name $ALBERTMU_ELASTIC_C_NAME \
 --privileged=true \
 --restart=always \
 --net $VNET_NAME \
 -p 9200:9200 -p 9300:9300 \
 -e "ES_JAVA_OPTS=-Xms1g -Xmx1g" \
 -v ${home}/data:/usr/share/elasticsearch/data \
 -v ${home}/logs:/usr/share/elasticsearch/logs \
 -v ${home}/plugins:/usr/share/elasticsearch/plugins \
 elasticsearch:$ALBERTMU_EK_VERSION
while ((1))
do
    container_info=`docker ps -a | grep ${ALBERTMU_ELASTIC_C_NAME}`
    if [[ $container_info =~ 'Up' ]]; then
        echo '容器已启动成功！'
        break
    fi
    sleep 1
done
sleep 32
echo '开始初始化elastic！'
echo y | docker exec -i ${ALBERTMU_ELASTIC_C_NAME} /usr/share/elasticsearch/bin/elasticsearch-reset-password -u elastic > ${home}/password.log && docker exec -it ${ALBERTMU_ELASTIC_C_NAME} /usr/share/elasticsearch/bin/elasticsearch-create-enrollment-token -s kibana > ${home}/token.log
echo 'elastic初始化成功！'

docker run -d --name ${ALBERTMU_KIBANA_C_NAME} \
 --privileged=true \
 --restart=always \
 --net $VNET_NAME \
 -p 5601:5601 \
 kibana:$ALBERTMU_EK_VERSION
while ((1))
do
    container_info=`docker ps -a | grep ${ALBERTMU_KIBANA_C_NAME}`
    if [[ $container_info =~ 'Up' ]]; then
        echo '容器已启动！'
        break
    fi
    sleep 1
done
cat ${home}/token.log
ip=`ifconfig -a|grep inet|grep 192 | grep -v inet6|awk "{print $2}"|tr -d "addr:" | awk '{print $2}'`
echo -n "请访问 http://${ip}:5601 开始配对，然后输入[y|Y]生成验证码。"
read keep
if [[ $keep == 'y' || $keep == 'Y' ]]; then
    echo '开始初始化kibana！'
    docker exec -it ${ALBERTMU_KIBANA_C_NAME} /usr/share/kibana/bin/kibana-verification-code > ${home}/verification-code.log
    echo 'kibana初始化成功！'
    sleep 3
    echo 'ek已部署完毕！'
    cat ${home}/verification-code.log
    cat ${home}/password.log
else
    echo '你已放弃配对，请卸载后重试或手动重试！'
fi
